#include <getopt.h>

#include "server/ServicePublisher.h"

#define VERSION 0.1

void print_usage(const char* program_name, int exit_code) {
	std::cout << program_name << " " << VERSION << "\n";
	std::cout << "Usage: " << program_name << " [options]\n\n";
	std::cout
			<< " -c, --config-file FILE   Load server configurations from specified\n";
	std::cout << "                          file. Default: server.cfg\n\n";
	std::cout << " -v, --verbose            Print verbose messages\n";
	std::cout << " -V, --version            Print program version\n";
	std::cout << " -h, --help               Print this help information\n\n";
	std::cout << "Report bugs to jrsj2@cin.ufpe.br.\n";

	exit(exit_code);
}

void print_version(const char* program_name) {
	std::cout << program_name << " " << VERSION << std::endl;

	exit(0);
}

int main(int argc, char **argv) {
	const char* program_name = argv[0];
	const option long_options[] = { { "config", 1, NULL, 'c' }, { "verbose", 0,
			NULL, 'v' }, { "version", 0, NULL, 'r' }, { "help", 0, NULL, 'h' },
			{ NULL, 0, NULL, 0 } };
	const char* short_options = "c:vrh";
	int next_opt;

	std::string config_file("server.cfg");
	Log::verbose_mode = false;

	do {
		next_opt = getopt_long(argc, argv, short_options, long_options, NULL);

		switch (next_opt) {
		case 'c':
			config_file = optarg;
			break;
		case 'v':
			Log::verbose_mode = true;
			break;
		case 'r':
			print_version(program_name);
		case 'h':
			print_usage(program_name, 0);
		case '?':
			print_usage(program_name, 1);
		case -1:
			break;
		default:
			abort();
		}
	} while (next_opt != -1);

	Log::verbose("Initializing..");

	Configuration config(config_file);
	if (!config.read_configuration())
		exit(1);

	try {
		ServicePublisher::publish();
	} catch (std::exception &ex) {
		Log::error(ex.what());
		return 1;
	}

	return 0;
}
